﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;

namespace Behaviours
{
    class TimeLineBehaviour : Behavior<MediaElement>
    {
        #region DEPENDENCY PROPERTY
        public static readonly DependencyProperty PositionProp =
        DependencyProperty.Register("Position", typeof(TimeSpan), typeof(TimeLineBehaviour),
                                    new PropertyMetadata(new PropertyChangedCallback( (d, e) =>
                                                         ((TimeLineBehaviour)d).PropertyChanged((TimeSpan)e.OldValue, (TimeSpan)e.NewValue))));

        public static readonly DependencyProperty MaximumProp = DependencyProperty.Register("Maximum", typeof(double), typeof(TimeLineBehaviour), new PropertyMetadata(default(double)));
        #endregion

        #region fields

        private Timer mTimer = new Timer(1000);

        #endregion

        #region properties

        public double Maximum
        {
            get { return (double)GetValue(MaximumProp); }
            set { SetValue(MaximumProp, value); }
        }

        public TimeSpan Position
        {
            get { return (TimeSpan)GetValue(PositionProp); }
            set
            {
                SetValue(PositionProp, value);
            }
        }

        #endregion

        #region methods

        protected override void OnAttached()
        {
            base.OnAttached();
            mTimer.Elapsed += mTimer_Elapsed;
            AssociatedObject.MediaOpened += AssociatedObject_MediaOpened;
            mTimer.Start();

        }

        void AssociatedObject_MediaOpened(object sender, RoutedEventArgs e)
        {
            Maximum = AssociatedObject.NaturalDuration.TimeSpan.TotalSeconds;
        }

        void mTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            Dispatcher.BeginInvoke(new Action(() => { Position = AssociatedObject.Position; }));
        }

        public void PropertyChanged(TimeSpan oldValue, TimeSpan newValue)
        {
            AssociatedObject.Position = newValue;
        }

        protected override void OnDetaching()
        {

            mTimer.Stop();
            mTimer.Elapsed -= mTimer_Elapsed;
            base.OnDetaching();
        }


        #endregion

    }
}
